/**
 * 泳道图ViewModel
 * 
 * 该文件实现了泳道图的数据管理和状态控制
 * 负责数据的实时更新、缓存管理和动画状态控制
 * 
 * 功能：
 * - 管理脑波数据的实时更新
 * - 控制数据缓存和时间窗口
 * - 提供数据流给UI组件
 * - 处理数据的平滑过渡和动画
 * 
 * 使用方法：
 * - 在Compose组件中使用viewModel()获取实例
 * - 通过collectAsState()观察数据变化
 * - 调用updateData()方法更新数据
 * 
 * 原理：
 * - 使用StateFlow管理响应式数据流
 * - 维护固定大小的数据缓存
 * - 自动清理过期数据
 */

package com.example.brain_wave.ui.components

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import java.util.concurrent.ConcurrentLinkedQueue

/**
 * 泳道图ViewModel
 */
class SwimLaneChartViewModel : ViewModel() {
    
    // 数据缓存队列
    private val dataCache = ConcurrentLinkedQueue<BrainWaveDataPoint>()
    
    // 配置
    private val _config = MutableStateFlow(SwimLaneChartConfig())
    val config: StateFlow<SwimLaneChartConfig> = _config.asStateFlow()
    
    // 数据流
    private val _dataPoints = MutableStateFlow<List<BrainWaveDataPoint>>(emptyList())
    val dataPoints: StateFlow<List<BrainWaveDataPoint>> = _dataPoints.asStateFlow()
    
    // 动画状态
    private val _isAnimating = MutableStateFlow(false)
    val isAnimating: StateFlow<Boolean> = _isAnimating.asStateFlow()
    
    // 是否正在采集数据
    private val _isSimulating = MutableStateFlow(false)
    val isSimulating: StateFlow<Boolean> = _isSimulating.asStateFlow()
    
    init {
        // 启动数据清理任务
        startDataCleanupTask()
    }
    
    /**
     * 单个数据点更新
     */
    fun updateDataPoint(dataPoint: BrainWaveDataPoint) {
        viewModelScope.launch {
            // 验证数据有效性
            if (!dataPoint.isValid()) {
                return@launch
            }
            
            // 添加到缓存
            dataCache.offer(dataPoint)
            
            // 限制缓存大小
            while (dataCache.size > _config.value.maxDataPoints) {
                dataCache.poll()
            }
            
            // 更新数据流（应用时间窗口过滤）
            _dataPoints.value = getFilteredDataPoints()
        }
    }
    
    /**
     * 批量更新数据点
     */
    fun updateDataPoints(dataPoints: List<BrainWaveDataPoint>) {
        viewModelScope.launch {
            // 过滤有效数据
            val validDataPoints = dataPoints.filter { it.isValid() }
            
            // 添加到缓存
            validDataPoints.forEach { dataCache.offer(it) }
            
            // 限制缓存大小
            while (dataCache.size > _config.value.maxDataPoints) {
                dataCache.poll()
            }
            
            // 更新数据流
            _dataPoints.value = getFilteredDataPoints()
        }
    }
    
    /**
     * 根据时间窗口配置过滤数据点
     */
    private fun getFilteredDataPoints(): List<BrainWaveDataPoint> {
        val currentTime = System.currentTimeMillis()
        val timeWindowMs = _config.value.getDisplayTimeWindowMs()
        val cutoffTime = currentTime - timeWindowMs
        
        return dataCache.toList()
            .filter { it.timestamp >= cutoffTime }
            .sortedBy { it.timestamp }
    }
    
    /**
     * 清空数据
     */
    fun clearData() {
        viewModelScope.launch {
            dataCache.clear()
            _dataPoints.value = emptyList()
        }
    }
    
    /**
     * 更新配置
     */
    fun updateConfig(newConfig: SwimLaneChartConfig) {
        viewModelScope.launch {
            _config.value = newConfig
            // 配置更新后重新过滤数据
            _dataPoints.value = getFilteredDataPoints()
        }
    }
    
    /**
     * 更新显示时间窗口
     */
    fun updateDisplayTimeWindow(seconds: Int) {
        val newConfig = _config.value.copy(displayTimeWindowSeconds = seconds)
        updateConfig(newConfig)
    }
    
    /**
     * 开始数据采集
     * 默认1000ms间隔，与实际蓝牙数据发送频率保持一致
     */
    fun startSimulation(intervalMs: Long = 1000L) {
        if (_isSimulating.value) return
        
        viewModelScope.launch {
            _isSimulating.value = true
            
            while (_isSimulating.value) {
                val dataPoint = BrainWaveDataGenerator.generateRandomDataPoint()
                updateDataPoint(dataPoint)
                delay(intervalMs)
            }
        }
    }
    
    /**
     * 停止数据采集
     */
    fun stopSimulation() {
        _isSimulating.value = false
    }
    
    /**
     * 启动数据清理任务
     * 定期清理过期数据
     */
    private fun startDataCleanupTask() {
        viewModelScope.launch {
            while (true) {
                delay(5000L) // 每5秒清理一次
                
                val currentTime = System.currentTimeMillis()
                val timeWindow = _config.value.timeWindowMs
                
                // 移除过期数据
                val iterator = dataCache.iterator()
                while (iterator.hasNext()) {
                    val dataPoint = iterator.next()
                    if (currentTime - dataPoint.timestamp > timeWindow) {
                        iterator.remove()
                    }
                }
                
                // 更新数据流
                _dataPoints.value = dataCache.toList().sortedBy { it.timestamp }
            }
        }
    }
    
    /**
     * 获取当前数据统计信息
     */
    fun getDataStatistics(): DataStatistics {
        val currentData = _dataPoints.value
        if (currentData.isEmpty()) {
            return DataStatistics()
        }
        
        val latest = currentData.last()
        val timeSpan = if (currentData.size > 1) {
            currentData.last().timestamp - currentData.first().timestamp
        } else {
            0L
        }
        
        return DataStatistics(
            totalPoints = currentData.size,
            timeSpanMs = timeSpan,
            latestTimestamp = latest.timestamp,
            averageFrequencies = calculateAverageFrequencies(currentData)
        )
    }
    
    /**
     * 计算平均频域值
     */
    private fun calculateAverageFrequencies(dataPoints: List<BrainWaveDataPoint>): Map<BrainWaveFrequency, Float> {
        if (dataPoints.isEmpty()) return emptyMap()
        
        val sums = mutableMapOf<BrainWaveFrequency, Float>()
        BrainWaveFrequency.values().forEach { frequency ->
            sums[frequency] = dataPoints.map { it.getRatioForFrequency(frequency) }.average().toFloat()
        }
        
        return sums
    }
}

/**
 * 数据统计信息
 */
data class DataStatistics(
    val totalPoints: Int = 0,
    val timeSpanMs: Long = 0L,
    val latestTimestamp: Long = 0L,
    val averageFrequencies: Map<BrainWaveFrequency, Float> = emptyMap()
)